<template>
  <div class="study-plan-container">
    <div class="page-header">
      <h2>学习计划管理</h2>
      <el-button type="primary" @click="showCreateDialog">创建新计划</el-button>
    </div>

    <!-- 学习计划列表 -->
    <div class="plan-list">
      <el-table :data="studyPlans" stripe style="width: 100%">
        <el-table-column prop="planName" label="计划名称" width="180" />
        <el-table-column prop="planType" label="计划类型" width="120">
          <template #default="scope">
            <el-tag :type="getPlanTypeTag(scope.row.planType)">
              {{ getPlanTypeLabel(scope.row.planType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ scope.row.startDate || '—' }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ scope.row.endDate || '—' }}
          </template>
        </el-table-column>
        <el-table-column prop="dailyTarget" label="每日目标" width="100">
          <template #default="scope">
            {{ scope.row.dailyTarget || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="currentProgress" label="当前进度" width="180">
          <template #default="scope">
            <el-progress 
              :percentage="calculateProgress(scope.row)" 
              :status="getProgressStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.status === 2"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建/编辑计划对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑学习计划' : '创建学习计划'"
      width="600px"
    >
      <el-form
        ref="planFormRef"
        :model="planForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="计划类型" prop="planType">
          <el-select v-model="planForm.planType" placeholder="请选择计划类型" style="width: 100%">
            <el-option label="每日学习" value="daily" />
            <el-option label="每周目标" value="weekly" />
            <el-option label="月度计划" value="monthly" />
            <el-option label="长期目标" value="long-term" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划内容" prop="planContent">
          <el-input
            v-model="planForm.planContent"
            type="textarea"
            :rows="4"
            placeholder="请输入计划内容，例如：每天完成2个章节的学习，包括课后习题"
          />
        </el-form-item>
        <el-form-item label="计划时间" prop="dateRange">
          <el-date-picker
            v-model="planForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="YYYY-MM-DD"
            style="width: 100%"
            :disabled-date="disablePastDates"
            @change="handleDateRangeChange"
          />
          <div class="date-tip" v-if="planForm.dateRange && planForm.dateRange[1]">
            <span>计划周期：{{ calculateDays(planForm.dateRange[0], planForm.dateRange[1]) }} 天</span>
          </div>
        </el-form-item>
        <el-form-item label="每日目标" prop="dailyTarget">
          <el-input-number
            v-model="planForm.dailyTarget"
            :min="1"
            :max="100"
            placeholder="请输入每日目标题数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId)

// 数据
const studyPlans = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const planFormRef = ref(null)

const planForm = ref({
  planName: '',
  planType: '',
  planContent: '',
  startDate: '',
  endDate: '',
  dateRange: [],
  dailyTarget: 10,
  status: 0,
  currentProgress: 0
})

// 表单验证规则
const rules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  planType: [
    { required: true, message: '请选择计划类型', trigger: 'change' }
  ],
  planContent: [
    { required: true, message: '请输入计划内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择计划时间范围', trigger: 'change' },
    { type: 'array', len: 2, message: '请选择开始和结束日期', trigger: 'change' }
  ],
  dailyTarget: [
    { required: true, message: '请输入每日目标', trigger: 'blur' },
    { type: 'number', min: 1, message: '每日目标必须大于0', trigger: 'blur' }
  ]
}

// 获取学习计划列表
const fetchStudyPlans = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/schedules/findbyid/${userId.value}`)
    
    // 将日程数据转换为学习计划格式
    studyPlans.value = response.data.map(item => {
      // 尝试从内容中提取计划名称和内容
      let planName = '学习计划';
      let planContent = item.content;
      
      if (item.content && item.content.includes(':')) {
        const parts = item.content.split(':', 2);
        planName = parts[0].trim();
        planContent = parts.length > 1 ? parts[1].trim() : '';
      }
      
      return {
        planId: item.scheduleId,
        userId: item.userId,
        planName: planName,
        planContent: planContent,
        planType: 'daily', // 默认类型
        startDate: formatDate(item.scheduleDate),
        endDate: formatDate(item.scheduleDate), // 日程没有结束日期，使用相同日期
        dailyTarget: 10, // 默认目标
        status: item.isCompleted === 1 ? 2 : 1, // 转换状态
        currentProgress: 0
      }
    })
  } catch (error) {
    console.error('获取学习计划失败:', error)
    ElMessage.error('获取学习计划失败')
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  const today = new Date()
  const todayStr = formatDateToString(today)
  
  // 默认结束日期为30天后
  const endDate = new Date(today)
  endDate.setDate(endDate.getDate() + 30)
  const endDateStr = formatDateToString(endDate)
  
  planForm.value = {
    planName: '',
    planType: 'daily',
    planContent: '',
    startDate: todayStr,
    endDate: endDateStr,
    dateRange: [todayStr, endDateStr],
    dailyTarget: 10,
    status: 0,
    currentProgress: 0
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true
  planForm.value = { ...row }
  // 设置日期范围
  planForm.value.dateRange = [row.startDate, row.endDate]
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该学习计划吗？', '提示', {
      type: 'warning'
    })
    
    await axios.delete(`http://localhost:8080/schedules/delete/${row.planId}`)
    ElMessage.success('删除成功')
    fetchStudyPlans()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学习计划失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!planFormRef.value) return
  
  try {
    await planFormRef.value.validate()
    
    // 确保日期从日期范围中获取
    if (planForm.value.dateRange && planForm.value.dateRange.length === 2) {
      planForm.value.startDate = planForm.value.dateRange[0]
      planForm.value.endDate = planForm.value.dateRange[1]
    } else {
      // 如果没有日期范围，使用默认值
      const today = new Date()
      planForm.value.startDate = formatDateToString(today)
      
      const endDate = new Date(today)
      endDate.setDate(endDate.getDate() + 30)
      planForm.value.endDate = formatDateToString(endDate)
    }
    
    console.log('提交的学习计划数据:', planForm.value)
    
    if (isEdit.value) {
      // 转换为日程表接口需要的格式
      const schedulePayload = {
        scheduleId: planForm.value.planId,
        userId: userId.value,
        content: `${planForm.value.planName}: ${planForm.value.planContent}`,
        scheduleDate: planForm.value.startDate,
        startTime: null,
        endTime: null,
        isCompleted: planForm.value.status === 2 ? 1 : 0
      }
      
      console.log('更新的日程数据:', schedulePayload)
      const response = await axios.put('http://localhost:8080/schedules/update', schedulePayload)
      console.log('更新学习计划响应:', response.data)
      ElMessage.success('更新成功')
    } else {
      // 转换为日程表接口需要的格式
      const schedulePayload = {
        userId: userId.value,
        content: `${planForm.value.planName}: ${planForm.value.planContent}`,
        scheduleDate: planForm.value.startDate,
        startTime: null,
        endTime: null,
        isCompleted: 0,
        createTime: new Date().toISOString()
      }
      
      console.log('转换后的日程数据:', schedulePayload)
      const response = await axios.post('http://localhost:8080/schedules/add', schedulePayload)
      console.log('创建学习计划响应:', response.data)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchStudyPlans()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      console.error('错误状态码:', error.response.status)
      ElMessage.error(`提交失败: ${error.response.data?.message || '服务器错误'}`)
    } else if (error.request) {
      console.error('未收到响应:', error.request)
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('请求配置错误')
    }
  }
}

// 获取计划类型标签
const getPlanTypeLabel = (type) => {
  const typeMap = {
    'daily': '每日学习',
    'weekly': '每周目标',
    'monthly': '月度计划',
    'long-term': '长期目标'
  }
  return typeMap[type] || '未知类型'
}

// 获取计划类型标签样式
const getPlanTypeTag = (type) => {
  const typeMap = {
    'daily': 'success',
    'weekly': 'warning',
    'monthly': 'info',
    'long-term': 'danger'
  }
  return typeMap[type] || 'default'
}

// 获取状态标签
const getStatusLabel = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已放弃'
    default: return '未知'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    case 3: return 'danger'
    default: return 'default'
  }
}

// 计算进度
const calculateProgress = (plan) => {
  if (!plan.currentProgress || !plan.dailyTarget) return 0
  return Math.min(100, Math.round((plan.currentProgress / plan.dailyTarget) * 100))
}

// 获取进度状态
const getProgressStatus = (plan) => {
  const progress = calculateProgress(plan)
  if (progress === 100) return 'success'
  if (progress >= 80) return 'warning'
  return ''
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return ''
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return ''
  }
}

// 格式化日期为字符串 YYYY-MM-DD
const formatDateToString = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 禁用过去的日期
const disablePastDates = (date) => {
  return date < new Date(new Date().setHours(0, 0, 0, 0))
}

// 计算日期范围
const calculateDays = (startDate, endDate) => {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 处理日期范围变化
const handleDateRangeChange = (value) => {
  if (value && value.length === 2) {
    planForm.value.startDate = value[0]
    planForm.value.endDate = value[1]
  }
}

// 初始化
onMounted(() => {
  fetchStudyPlans()
})
</script>

<style scoped>
.study-plan-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.plan-list {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.date-tip {
  margin-top: 8px;
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
}

.date-tip span {
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

:deep(.el-date-editor--daterange) {
  width: 100%;
}

:deep(.el-date-editor .el-range-separator) {
  padding: 0 8px;
  line-height: 32px;
  width: 5%;
  color: #909399;
}

:deep(.el-progress-bar__outer) {
  background-color: rgba(107, 155, 210, 0.1);
}

:deep(.el-progress-bar__inner) {
  transition: all 0.3s ease;
}

:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px rgba(107, 155, 210, 0.1);
}
</style> 